const app = getApp();
Page({
  data: {
    inputValue: '', 
    messages: [],   
    InputBottom: 0, 
    isThinking: false
  },

  toggleThinking() {
    this.setData({
      isThinking: !this.data.isThinking
    });
  },

  // 用户输入框内容变化时触发
  inputChange(e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

  
  sendMessage() {
    const inputValue = this.data.inputValue.trim();
    if (!inputValue) return;

    const time = this.formatTime(new Date());
    const userMessage = {
      avatar: 'https://image.meiye.art/Fha6tqRTIwHtlLW3xuZBJj8ZXSX3?imageMogr2/thumbnail/450x/interlace/1',
      content: inputValue,
      time: time,
      from: 'user'
    };

    const messages = this.data.messages.concat(userMessage);
    this.setData({
      messages: messages,
      inputValue: '' 
    });

    this.scrollToBottom(); 

    
    this.sendToDeepSeek(inputValue);
  },

  
  sendToDeepSeek: async function(inputValue) {
    const model = wx.cloud.extend.AI.createModel("deepseek");
    const selectedModel = this.data.isThinking ? "deepseek-r1" : "deepseek-v3";

    console.log(`当前使用的模型: ${selectedModel}`);

    const res = await model.streamText({
      data: {
        model: selectedModel,
        messages: [
          { role: "user", content: inputValue },
        ],
      },
    });

    let response = '';
    let messages = this.data.messages;

    const aiMessage = {
      avatar: 'https://image.meiye.art/FlqKg5bugFQD5Qzm_QhGM7ET4Mtx?imageMogr2/thumbnail/450x/interlace/1',
      content: '',
      time: this.formatTime(new Date()),
      from: 'ai'
    };

    messages.push(aiMessage);
    this.setData({ messages: messages });

    this.scrollToBottom(); 

    for await (let str of res.textStream) {
      response += str;
      messages[messages.length - 1].content = response;
      this.setData({ messages: messages });
      this.scrollToBottom(); 
    }
  },

 
  scrollToBottom() {
    this.createSelectorQuery().select('#chatBox').boundingClientRect(rect => {
      if (rect) {
        wx.pageScrollTo({
          scrollTop: rect.height,
          duration: 300
        });
      }
    }).exec();
  },

 
  formatTime(date) {
    const hour = date.getHours();
    const minute = date.getMinutes();
    return `${hour}:${minute < 10 ? '0' + minute : minute}`;
  },

  
  InputFocus(e) {
    this.setData({
      InputBottom: e.detail.height
    });
  },

  InputBlur() {
    this.setData({
      InputBottom: 0
    });
  }
});
